import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from '../components/Login.vue'
import DashboardView from '../views/DashboardView.vue'
import DeptManage from '../views/DeptManage.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: HomeView,
      children: [
        {
          path: '',
          name: 'Dashboard',
          component: DashboardView
        },
        {
          path: '/admin/schedule-preview',
          name: 'AdminSchedulePreview',
          component: () => import('../views/AdminSchedulePreview.vue')
        },
        {
          path: 'dept/dept',
          name: 'DeptManage',
          component: DeptManage
        },
        {          path: 'schedule/preview-home',          name: 'SchedulePreviewHome',          component: () => import('../views/AdminSchedulePreview.vue')        },        {          path: 'schedule/preview',          name: 'SchedulePreview',          component: () => import('../views/AdminSchedulePreview.vue')        }
      ]
    },
    {
      path: '/about',
      name: 'About',
      component: () => import('../views/AboutView.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 每次都检查登录状态，确保即使用户刷新页面也能正确处理
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  
  console.log('当前登录状态:', isLoggedIn);
  console.log('当前访问路径:', to.path);
  
  // 如果已登录且要去登录页，则重定向到主页
  if (isLoggedIn && to.path === '/') {
    console.log('已登录，重定向到首页');
    next('/home');
  } 
  // 如果未登录且要去登录页，正常放行
  else if (!isLoggedIn && to.path === '/') {
    next();
  }
  // 如果未登录且不去登录页，则重定向到登录页，并记录目标路径
  else if (!isLoggedIn && to.path !== '/') {
    console.log('未登录，重定向到登录页');
    next({ path: '/', query: { redirect: to.fullPath } });
  } 
  // 已登录用户正常放行
  else {
    next();
  }
});

// 移除不必要的 afterEach 钩子

export default router